<template>
  <div class="borrow-list">
    <div class="page-header">
      <h2>借阅管理</h2>
    </div>

    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-form :model="searchForm" :inline="true">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item label="图书标题">
              <el-input v-model="searchForm.bookTitle" placeholder="请输入图书标题" clearable />
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="借阅中" :value="0" />
                <el-option label="已归还" :value="1" />
                <el-option label="逾期" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleAdd">添加借阅</el-button>
        </el-col>
      </el-row>
    </div>

    <div class="table-section">
      <el-table v-loading="loading" :data="tableData" stripe border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="bookTitle" label="图书标题" min-width="200" />
        <el-table-column prop="borrowDate" label="借阅日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="归还日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.returnDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">查看</el-button>
            <el-button v-if="row.status === 0" type="success" size="small" @click="handleReturn(row)">归还</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageNo"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import borrowApi from '@/api/borrow'

const router = useRouter()

const loading = ref(false)
const tableData = ref([])

const searchForm = reactive({
  username: '',
  bookTitle: '',
  status: null
})

const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

const getBorrowList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize
    }

    const result = await borrowApi.getList(params)
    if (result) {
      tableData.value = result.result || []
      pagination.total = result.total || 0
    }
  } catch (error) {
    ElMessage.error('获取借阅列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNo = 1
  getBorrowList()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'status' ? null : ''
  })
  pagination.pageNo = 1
  getBorrowList()
}

const handleAdd = () => {
  router.push('/borrow/add')
}

const handleView = (row) => {
  ElMessage.info('查看功能开发中')
}

const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要归还这本图书吗？', '归还确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await borrowApi.return(row.id)
    ElMessage.success('归还成功')
    getBorrowList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('归还失败: ' + error.message)
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条借阅记录吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await borrowApi.delete(row.id)
    ElMessage.success('删除成功')
    getBorrowList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNo = 1
  getBorrowList()
}

const handleCurrentChange = (page) => {
  pagination.pageNo = page
  getBorrowList()
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

const getStatusType = (status) => {
  const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = { 0: '借阅中', 1: '已归还', 2: '逾期' }
  return textMap[status] || '未知'
}

onMounted(() => {
  getBorrowList()
})
</script>

<style scoped>
.borrow-list {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
}
</style>
